package top.alanshelby.mybatis.util;

        import org.apache.ibatis.type.BaseTypeHandler;
        import org.apache.ibatis.type.JdbcType;

        import java.sql.CallableStatement;
        import java.sql.PreparedStatement;
        import java.sql.ResultSet;
        import java.sql.SQLException;
        import java.util.Date;

public class MyDateTypeHandler extends BaseTypeHandler<Date> {

    /**
     * 将时间戳字符串存入数据库
     */
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Date parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, String.valueOf(parameter.getTime()));
    }

    /**
     * 把时间戳类型的字符串取出转换为Date
     */
    @Override
    public Date getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String sqlTime = rs.getString(columnName);
        if (null != sqlTime) {
            return new Date(Long.valueOf(sqlTime));
        }
        return null;
    }

    /**
     * 把时间戳类型的字符串取出转换为Date
     */
    @Override
    public Date getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String sqlTime = rs.getString(columnIndex);
        if (null != sqlTime) {
            return new Date(Long.valueOf(sqlTime));
        }
        return null;
    }

    /**
     * 把时间戳类型的字符串取出转换为Date
     */
    @Override
    public Date getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String sqlTime = cs.getString(columnIndex);
        if (null != sqlTime) {
            return new Date(Long.valueOf(sqlTime));
        }
        return null;
    }
}